const hre = require('hardhat');
/**
 * 向指定 launchId 购买代币 (bonding curve)
 * 环境变量:
 *  LAUNCHPAD_ADDRESS  LaunchPad 合约地址 (必填)
 *  LAUNCH_ID          要购买的 launchId (默认 1)
 *  ETH_AMOUNT         发送 ETH 数量 (默认 0.01)
 * 用法示例:
 *  LAUNCHPAD_ADDRESS=0xd9B7BDD6DbC80DaEc00fB0a6c920eA50C1eDF017 LAUNCH_ID=1 ETH_AMOUNT=0.01 \
 *  npx hardhat run scripts/buy-tokens.js --network xlayerTerigon
 */
async function main(){
  const p = process.env;
  const launchPadAddr = p.LAUNCHPAD_ADDRESS;
  if(!launchPadAddr) throw new Error('请设置 LAUNCHPAD_ADDRESS 环境变量。示例: LAUNCHPAD_ADDRESS=0xd9B7BDD6DbC80DaEc00fB0a6c920eA50C1eDF017');
  const launchId = p.LAUNCH_ID ? parseInt(p.LAUNCH_ID) : 1;
  const ethAmountStr = p.ETH_AMOUNT || '0.01';
  if(isNaN(Number(ethAmountStr)) || Number(ethAmountStr) <= 0) throw new Error('ETH_AMOUNT 必须为正数');

  console.log('=== Buy Tokens ===');
  console.log('Network:', hre.network.name);
  console.log('LaunchPad:', launchPadAddr);
  console.log('Launch ID:', launchId);
  console.log('ETH Amount:', ethAmountStr);

  const [signer] = await hre.ethers.getSigners();
  const addr = await signer.getAddress();
  console.log('Buyer:', addr);
  console.log('Buyer Balance Before:', hre.ethers.formatEther(await signer.provider.getBalance(addr)));

  const launchPad = await hre.ethers.getContractAt('XLayerLaunchPad', launchPadAddr, signer);
  const infoBefore = await launchPad.getLaunchInfo(launchId);
  const tokenAddress = infoBefore[0];
  const raisedBefore = infoBefore[6];
  const priceBefore = infoBefore[10];
  const soldBefore = infoBefore[11];
  console.log('Token Address:', tokenAddress);
  console.log('Price Before (ETH):', hre.ethers.formatEther(priceBefore));
  console.log('Raised Before (ETH):', hre.ethers.formatEther(raisedBefore));
  console.log('Tokens Sold Before:', soldBefore.toString());

  const tx = await launchPad.buyTokens(launchId, { value: hre.ethers.parseEther(ethAmountStr) });
  console.log('Submitted tx:', tx.hash);
  const receipt = await tx.wait();
  console.log('Mined block:', receipt.blockNumber);

  const infoAfter = await launchPad.getLaunchInfo(launchId);
  const raisedAfter = infoAfter[6];
  const priceAfter = infoAfter[10];
  const soldAfter = infoAfter[11];

  // 读取用户代币余额 (内部跟踪 + 真实 ERC20 余额)
  const token = await hre.ethers.getContractAt(['function balanceOf(address) view returns(uint256)','function symbol() view returns(string)'], tokenAddress, signer);
  const bal = await token.balanceOf(addr);
  const symbol = await token.symbol();

  console.log('\n=== After Purchase ===');
  console.log('Price After (ETH):', hre.ethers.formatEther(priceAfter));
  console.log('Raised After (ETH):', hre.ethers.formatEther(raisedAfter));
  console.log('Tokens Sold After:', soldAfter.toString());
  console.log('Your Token Balance:', bal.toString(), symbol);
  console.log('Buyer Balance After:', hre.ethers.formatEther(await signer.provider.getBalance(addr)));
  console.log('\n完成: 购买成功。');
}

main().catch(e=>{console.error(e);process.exit(1);});
